import React, { useState, useEffect } from "react";
import { Table, Button, Form, Input, Select, Modal, message } from "antd";
import {
  SearchOutlined,
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
} from "@ant-design/icons";
import { adminAPI } from "../services/api";

const { Option } = Select;

const GuestManagement = () => {
  const [form] = Form.useForm();
  const [guests, setGuests] = useState([]);
  const [loading, setLoading] = useState(false);
  const [modalVisible, setModalVisible] = useState(false);
  const [editingGuest, setEditingGuest] = useState(null); // Stores guest data when editing

  useEffect(() => {
    fetchGuests(); // Fetch all guests on component mount
  }, []);

  // Fetches guests based on search parameters
  const fetchGuests = async (params = {}) => {
    setLoading(true);
    try {
      const { data } = await adminAPI.searchGuests(params); // Use adminAPI.searchGuests
      setGuests(data);
    } catch (error) {
      message.error("获取客户列表失败");
      console.error("Error fetching guests:", error);
    } finally {
      setLoading(false);
    }
  };

  // Handles search form submission
  const handleSearch = (values) => {
    fetchGuests(values);
  };

  // Opens modal for adding a new guest
  const handleAdd = () => {
    setEditingGuest(null); // Clear editing state
    form.resetFields(); // Clear form fields
    setModalVisible(true);
  };

  // Opens modal for editing an existing guest
  const handleEdit = (record) => {
    setEditingGuest(record); // Set guest data for editing
    form.setFieldsValue(record); // Populate form fields with existing data
    setModalVisible(true);
  };

  // Handles deleting a guest
  const handleDelete = (guestId) => {
    Modal.confirm({
      title: "确认删除?",
      content:
        "确定要删除该客户吗? 删除客户将同时删除其相关联的消费记录和入住记录，但不能删除有正在入住的记录的客户。",
      okText: "删除",
      cancelText: "取消",
      onOk: async () => {
        try {
          await adminAPI.deleteGuest(guestId); // Use adminAPI.deleteGuest
          message.success("客户删除成功");
          fetchGuests(); // Refresh list after deletion
        } catch (error) {
          message.error(
            "删除失败: " + (error.response?.data?.message || error.message)
          );
          console.error("Error deleting guest:", error);
        }
      },
    });
  };

  // Handles form submission (add or update)
  const onFinish = async (values) => {
    try {
      if (editingGuest) {
        // If editing, call updateGuest API
        await adminAPI.updateGuest(editingGuest.guest_id, values);
        message.success("客户信息更新成功");
      } else {
        // If adding, call addGuest API
        await adminAPI.addGuest(values);
        message.success("客户添加成功");
      }
      setModalVisible(false); // Close modal
      fetchGuests(); // Refresh guest list
    } catch (error) {
      message.error(
        (editingGuest ? "更新失败: " : "添加失败: ") +
          (error.response?.data?.message || error.message)
      );
      console.error("Error saving guest:", error);
    }
  };

  // Table columns definition
  const columns = [
    { title: "姓名", dataIndex: "name", key: "name" },
    { title: "性别", dataIndex: "gender", key: "gender" },
    { title: "身份证号", dataIndex: "id_card", key: "id_card" },
    { title: "电话", dataIndex: "phone", key: "phone" },
    {
      title: "操作",
      key: "action",
      render: (_, record) => (
        <div>
          <Button
            type="link"
            icon={<EditOutlined />}
            onClick={() => handleEdit(record)}
          >
            编辑
          </Button>
          <Button
            type="link"
            danger
            icon={<DeleteOutlined />}
            onClick={() => handleDelete(record.guest_id)}
          >
            删除
          </Button>
        </div>
      ),
    },
  ];

  return (
    <div>
      <div
        style={{
          marginBottom: 16,
          display: "flex",
          justifyContent: "space-between",
        }}
      >
        <Form layout="inline" onFinish={handleSearch}>
          <Form.Item name="name">
            <Input placeholder="搜索姓名" prefix={<SearchOutlined />} />
          </Form.Item>
          <Form.Item name="id_card">
            <Input placeholder="搜索身份证号" prefix={<SearchOutlined />} />
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit">
              搜索
            </Button>
          </Form.Item>
        </Form>

        <Button type="primary" icon={<PlusOutlined />} onClick={handleAdd}>
          添加客户
        </Button>
      </div>

      <Table
        dataSource={guests}
        columns={columns}
        rowKey="guest_id"
        loading={loading}
        bordered // Add borders for better readability
      />

      <Modal
        title={editingGuest ? "编辑客户" : "添加客户"}
        open={modalVisible}
        onCancel={() => setModalVisible(false)}
        onOk={() => form.submit()} // Trigger form submission on OK
      >
        <Form form={form} layout="vertical" onFinish={onFinish}>
          <Form.Item
            name="name"
            label="姓名"
            rules={[{ required: true, message: "请输入姓名" }]}
          >
            <Input placeholder="输入姓名" />
          </Form.Item>

          <Form.Item
            name="gender"
            label="性别"
            rules={[{ required: true, message: "请选择性别" }]}
          >
            <Select placeholder="选择性别">
              <Option value="男">男</Option>
              <Option value="女">女</Option>
            </Select>
          </Form.Item>

          <Form.Item
            name="id_card"
            label="身份证号"
            rules={[
              { required: true, message: "请输入身份证号" },
              {
                pattern: /^\d{17}[\dX]$/i,
                message: "请输入有效的18位身份证号",
              }, // Basic regex validation
            ]}
          >
            <Input placeholder="输入身份证号" />
          </Form.Item>

          <Form.Item
            name="phone"
            label="电话"
            rules={[{ pattern: /^\d{11}$/, message: "请输入11位手机号码" }]} // Basic phone validation
          >
            <Input placeholder="输入联系电话" />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default GuestManagement;
